package structure.linkedList2;

public class MyDoubleLinkedList {

    private Node header;
    private Node tail;

    private int size;

    public Node get(Integer index) {
        if (index < 0 || index > size - 1) {
            return null;
        }
        if (index < size / 2) {
            Node node = header;
            for (int i = 0; i < index; i++) {
                node = node.next;
            }
            return node;
        } else {
            Node node = tail;
            for (int i = size - 1; i > index; i--) {
                node = node.pre;
            }
            return node;
        }
    }

    public void add(Integer value) {
        Node l = tail;
        Node node = new Node(value);

        tail = node;
        if (l == null) {
            header = node;
        } else {
            l.next = node;
            node.pre = l;
        }
        size++;
    }


    public void add(Integer index, Integer value) {

        if (index == size) {
            add(value);
        } else {
            Node newNode = new Node(value);
            Node node = get(index);
            Node pre = node.pre;

            if (pre == null) {
                newNode.next = header;
                header.pre = newNode;
                header = newNode;
            } else {
                pre.next = newNode;
                newNode.pre = pre;
            }


            newNode.next = node;
            node.pre = newNode;
            size++;
        }
    }

    // 从首节点删除
    public void delete() {
        if (header == null) {
            return;
        }
        Node next = header.next;
        if (next == null) {
            header = null;
            tail = null;
        } else {
            next.pre = null;
            header = next;
        }
        size--;
    }

    static class Node {
        private final Integer value;
        private Node next;
        private Node pre;


        Node(Integer value) {
            this.value = value;
        }
    }
}
